<template>
  <div class="app_content">
      <el-form :inline="true" ref="queryForm" :model="queryParams" class="demo-form-inline" :size="size" v-if="showSearch">
      <el-form-item label="部门名称" prop="deptName">
      <el-input v-model="queryParams.deptName" clearable placeholder="部门名称" style="width: 240px"/>
      </el-form-item>
      <el-form-item label="状态" prop="status">
      <el-input v-model="queryParams.status" clearable placeholder="状态" style="width: 240px"/>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="querySubmit">
          <component :theme="iconTheme" :size="iconSize" :strokeWidth="iconStrokeWidth" :is="'icon-search'"/>
          搜索</el-button>
        <el-button   @click="resetSubmit">
          <component :theme="iconTheme" :size="iconSize" :strokeWidth="iconStrokeWidth" :is="'icon-redo'"/>
          重置</el-button>
      </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            :size="size"
            @click="handleAdd"
            v-hasRole="['system:dept:add']"
          >
          <component :theme="iconTheme" :size="iconSize" :strokeWidth="iconStrokeWidth" :is="'icon-add-one'"/>
          新增</el-button>
        </el-col>
        <el-col :span="1.5">
        <el-button
          type="info"
          plain
          :size="size"
          @click="toggleExpandAll"
        >
        <component :theme="iconTheme" :size="iconSize" :strokeWidth="iconStrokeWidth" :is="'icon-menu-unfold'"/>
        展开/折叠</el-button>
      </el-col>
        <!-- <RightToolbar :showSearch="showSearch" @queryTable="getList" :columns="columns"/> -->
        <RightToolbar :showSearch="showSearch" @queryTable='getList' @showSearchClick='showSearchClick' :columns="columns"/>
      </el-row>
      <el-table v-if="refreshTable" :border="$border" :default-expand-all="isExpandAll" :height="maxHeight" row-key="deptId" :tree-props="{children: 'children', hasChildren: 'hasChildren'}" v-loading="loading" :data="tableData"  style="width: 100%" @selection-change="handleSelectionChange"  :size="size"
      >
      <el-table-column prop="deptName" label="部门名称" key="deptName" :show-overflow-tooltip="true"  v-if="columns[0].visible"></el-table-column>
      <el-table-column prop="orderNum" key="orderNum" label="排序"  v-if="columns[1].visible"></el-table-column>
      <el-table-column prop="status" key="status" label="状态" :formatter="statusFormat"  v-if="columns[2].visible">
      </el-table-column>
      <el-table-column label="创建时间"  prop="createTime" show-overflow-tooltip key="createTime"  v-if="columns[3].visible"/>
      <el-table-column label="操作" fixed="right" align="center"  width="300px">
      <template #default="scope">
        <el-button :size="size" type="success" text @click="handleEdit(scope.row)" v-hasRole="['system:dept:edit']"
          >
          <component :theme="iconTheme" :size="iconSize" :strokeWidth="iconStrokeWidth" :is="'icon-edit-one'"/>
          修改</el-button>
          <el-button :size="size" type="success" text @click="handleAdd(scope.row)" v-hasRole="['system:dept:add']"
          >
          <component :theme="iconTheme" :size="iconSize" :strokeWidth="iconStrokeWidth" :is="'icon-add-one'"/>
          新增</el-button>
          <el-button
          v-if="scope.row.parentId != 0"
          :size="size"
          type="danger"
          text
          @click="handleDelete(scope.row)"
          v-hasRole="['system:dept:remove']"
          >
          <component :theme="iconTheme" :size="iconSize" :strokeWidth="iconStrokeWidth" :is="'icon-delete-five'"/>
          删除</el-button>
      </template>
      </el-table-column>
      </el-table>
 
      <!-- <el-dialog  v-model="open"  :close-on-click-modal="false" :close-on-press-escape="false" :show-close="false" width="600px" append-to-body draggable :fullscreen="fullscreen">
      <template #header="{titleId, titleClass }">
      <div class="my-header">
        <span :id="titleId" :class="titleClass">{{title}}</span>
        <div>
          <component
        style="cursor:pointer;line-height: 24px;margin-right:10px;"
        v-if="fullscreen==false"
              @click="fullscreen=true"
              class="menu-icon"
              theme="outline"
              size="14"
              strokeWidth="3"
              :is="'icon-full-screen-one'"
            />
            <component
            v-else
        style="cursor:pointer;line-height: 24px;margin-right:10px;"
              @click="fullscreen=false"
              class="menu-icon"
              theme="outline"
              size="14"
              strokeWidth="3"
              :is="'icon-off-screen-one'"
            />
        <component
        style="cursor:pointer;line-height: 24px;"
              @click="cancel"
              class="menu-icon"
              theme="outline"
              size="14"
              strokeWidth="3"
              :is="'icon-close'"
            />
        </div>
        
      </div>
    </template>

    <el-form ref="formDataRef" :model="formData" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12" v-if="formData.parentId !== 0">
            <el-form-item label="上级部门" prop="parentId">
              <el-tree-select
                  v-model="formData.parentId"
                  :data="deptOptions"
                  check-strictly
                  :props="treeProps"
                  :render-after-expand="false"
                />
              
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="部门名称" prop="deptName">
              <el-input v-model="formData.deptName" placeholder="请输入部门名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="orderNum">
              <el-input-number v-model="formData.orderNum" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="负责人" prop="leader">
              <el-input v-model="formData.leader" placeholder="请输入负责人" maxlength="20" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="formData.phone" placeholder="请输入联系电话" maxlength="11" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="formData.email" placeholder="请输入邮箱" maxlength="50" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门状态">
              <el-radio-group v-model="formData.status">
                <el-radio
                  v-for="dict in statusOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                >{{dict.dictLabel}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div  class="dialog-footer">
        <el-button type="primary" @click="submitForm" :size="size">确 定</el-button>
        <el-button @click="cancel" :size="size">取 消</el-button>
      </div>
      </template>

    </el-dialog> -->
  
    <el-drawer
      :title="title"
      v-model="open"
      direction="rtl"
      destroy-on-close
      size="50%"
      :close-on-click-modal="false"
    >
    <el-form ref="formDataRef" :model="formData" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12" v-if="formData.parentId !== 0">
            <el-form-item label="上级部门" prop="parentId">
              <el-tree-select
                  v-model="formData.parentId"
                  :data="deptOptions"
                  check-strictly
                  :props="treeProps"
                  :render-after-expand="false"
                />
              <!-- <TreeSelect
              v-if="treeis"
              ref="myTreeSelect"
              @SelectValue="SelectValue"
              :modelValue="formData.parentId"
              :placeholder="'请选择上级部门'"
              :treeData="deptOptions"
              :defaultProps="{'id':'deptId','label':'deptName','children':'children','parentId':'parentId'}"
              ></TreeSelect>
              <el-input  v-loading="treeis" placeholder="请选择上级部门"  v-else/> -->
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="部门名称" prop="deptName">
              <el-input v-model="formData.deptName" placeholder="请输入部门名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="orderNum">
              <el-input-number v-model="formData.orderNum" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="负责人" prop="leader">
              <el-input v-model="formData.leader" placeholder="请输入负责人" maxlength="20" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="formData.phone" placeholder="请输入联系电话" maxlength="11" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="formData.email" placeholder="请输入邮箱" maxlength="50" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门状态">
              <el-radio-group v-model="formData.status">
                <el-radio
                  v-for="dict in statusOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                >{{dict.dictLabel}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div  class="dialog-footer">
          <el-button type="primary" @click="submitForm" :size="size">
          <component :theme="iconTheme" :size="iconSize" :strokeWidth="iconStrokeWidth" :is="'icon-correct'"/>
          确 定</el-button>
        <el-button @click="cancel" :size="size">
          <component :theme="iconTheme" :size="iconSize" :strokeWidth="iconStrokeWidth" :is="'icon-return'"/>
          取 消</el-button>
      </div>
      </template>
  </el-drawer>
  </div>
  
</template>

<script  >
import RightToolbar from '@/components/RightToolbar/index.vue';
import { listDept, getDept, delDept, addDept, updateDept, listDeptExcludeChild } from "@/api/system/dept";
import { computed, ref ,reactive,onMounted,getCurrentInstance,toRefs,nextTick} from 'vue'
import { useStore } from 'vuex';
// import TreeSelect from '@/components/TreeSelectDept/index.vue'
import { useI18n } from 'vue-i18n';
import {
Delete,
Edit,
Plus,
Switch
} from '@element-plus/icons-vue'

export default defineComponent({
  components:{
    // TreeSelect
  },
setup(){
  const { proxy } = getCurrentInstance();//关键代码
  const queryForm=ref(null)
  const formDataRef=ref(null)
  const { t } = useI18n();
  const store = useStore();
  const staticData=reactive({
    formData:{
     
    },
    // 表单校验
    rules: {
        parentId: [
          { required: true, message: "上级部门不能为空", trigger: "blur" }
        ],
        deptName: [
          { required: true, message: "部门名称不能为空", trigger: "blur" }
        ],
        orderNum: [
          { required: true, message: "显示排序不能为空", trigger: "blur" }
        ],
        email: [
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ],
        phone: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ]
      },
      treeProps:{
        label: 'deptName', // 设置节点显示的字段，默认为 'label'
        children: 'children', // 设置子节点的字段，默认为 'children'
        value:'deptId',
        isLeaf: 'leaf', // 设置判断是否叶子节点的字段，默认为 'isLeaf'
      },
    maxHeight:store.getters['setting/mode']=='horizontal'?document.body.clientHeight - 200:store.getters['setting/isFullScreen']!=false ?document.body.clientHeight - 360:document.body.clientHeight - 260,
    treeis:false,
    single:true,
    multiple:true,
    showSearch:true,
    background:false,
    disabled :false,
    search:'',
    tableData:[],
    // 部门树选项
    deptOptions: [],
    // 日期范围
    dateRange: [],
    // 菜单状态数据字典
    statusOptions: [],
    // 是否展开，默认全部展开
    isExpandAll: true,
    // 重新渲染表格状态
    refreshTable: true,
    //是否全屏
    fullscreen:false,
    // 是否显示弹出层
    open: false,
    // 弹出层标题
    title: "",
    // 查询参数
    queryParams: {
      deptName: undefined,
      status: undefined
    },
    total:0,
    loading:true, 
    ExportHead:{
      
    },
    // 列信息
    columns: [
      { key: 0, label: `部门名称`, visible: true },
      { key: 1, label: `显示顺序`, visible: true },
      { key: 2, label: `状态`, visible: true },
      { key: 3, label: `创建时间`, visible: true },

      
    ],
  })
  const size = computed(() => {
        return store.getters['setting/size'];
  });

  const small =computed(() => {
    return size.value=='small'?true:false
  });

  const filterTableData = computed(() =>
    staticData.tableData.filter(
      (data) =>
        !staticData.search.value ||
        data.name.toLowerCase().includes(staticData.search.value.toLowerCase())
    )
  )
  onMounted(() => {
      proxy.$getDicts("sys_normal_disable").then(response => {
        staticData.statusOptions = response.data;
      });
      proxy.getList()
  })

  /**
   * 重置表单效验方法
   */
  const resetForm = (formEl) => {
    if (!formEl.value) return
    formEl.value.resetFields()
  }
  
  const methods = {
    SelectValue(data){
      staticData.formData.parentId=data
      formDataRef.value.clearValidate('parentId');
    },
     getList(){
        staticData.loading = true;
        listDept(staticData.queryParams).then(
          response => {
            staticData.tableData = proxy.$handleTree(response.data, "deptId");
            staticData.loading = false;
          }
      );
     },
     
    // 部门状态字典翻译
    statusFormat(row, column) {
      const data=proxy.$selectDictLabel(staticData.statusOptions, row.status)
      let stateClass
      // if(data=='正常'){
      //   stateClass='status_success'
      // }else{
      //   stateClass='status_error'
      // }
      
      return data;
    },
     /** 展开/折叠操作 */
     toggleExpandAll() {
      staticData.refreshTable = false;
      staticData.isExpandAll = !staticData.isExpandAll;
      nextTick(() => {
        staticData.refreshTable = true;
      });
    },

     /**
      * 显示或隐藏搜索条件
      **/
     showSearchClick(data){
       staticData.showSearch=data
     },
     // 表单重置
    reset() {
      staticData.formData = {
        deptId: undefined,
        parentId: undefined,
        deptName: undefined,
        orderNum: undefined,
        leader: undefined,
        phone: undefined,
        email: undefined,
        status: "0"
      };
      resetForm(formDataRef)
    },
     handleAdd(row){
      proxy.reset();
      staticData.fullscreen=false
      if (row != undefined) {
        staticData.formData.parentId = row.deptId;
      }
      listDept().then(response => {
        staticData.deptOptions = proxy.$handleTree(response.data, "deptId");
        staticData.treeis=true
        staticData.open = true;
        staticData.title = "添加部门";
      });
    },
   

    handleEdit(row){
      proxy.reset();
      staticData.fullscreen=false
      getDept(row.deptId).then(response => {
        nextTick(()=>{
        staticData.formData = response.data;
        
        listDeptExcludeChild(row.deptId).then(response => {
          nextTick(()=>{
          staticData.deptOptions = proxy.$handleTree(response.data, "deptId");
          if (staticData.deptOptions.length == 0) {
            const noResultsOptions = { deptId: staticData.formData.parentId, deptName: staticData.formData.parentName, children: [] };
            staticData.deptOptions.push(noResultsOptions);
          }
          staticData.treeis=true 
        })
        });
      })
         
      });
      
      staticData.open = true;
      staticData.title = "修改部门";
    },
    handleDelete(row){
      ElMessageBox.confirm('是否确认删除名称为"' + row.deptName + '"的数据项？', t('confirm.title'), {
          confirmButtonText: t('btn.confirm'),
          cancelButtonText: t('btn.cancel'),
          type: "warning"
        })
      .then(function() {
        return delDept(row.deptId);
      }).then(() => {
        proxy.getList();
        proxy.Success("删除成功");
      }).catch(() => {});
      
    },
    handleSelectionChange(){

    },
    /**提交数据 */
    submitForm(){
      formDataRef.value.validate(valid => {
        if (valid) {
          if (staticData.formData.deptId != undefined) {
            updateDept(staticData.formData).then(response => {
              proxy.Success("修改成功");
              staticData.open = false;
              proxy.getList();
            });
          } else {
            addDept(staticData.formData).then(response => {
              proxy.Success("新增成功");
              staticData.open = false;
              proxy.getList();
            });
          }
        }
      });
    },
    /**关闭弹窗 */
    cancel(){
      staticData.treeis=false
      staticData.open = false;
    },
    resetSubmit(){
      staticData.dateRange=[]
      queryForm.value.resetFields();
      proxy.getList()
    },
    querySubmit(){
      staticData.queryParams.pageNum = 1;
      proxy.getList()
    },
    handleSizeChange (val) {
      console.log(`${val} items per page`)
      staticData.queryParams.pageSize =val;
      proxy.getList()
    },
    handleCurrentChange(val){
      console.log(`current page: ${val}`)
      staticData.queryParams.pageNum =val;
      proxy.getList()
    }
   }
    return {
      Delete,
      Edit,
      Plus,
      Switch,
      size,
      small,
      queryForm,
      formDataRef,
      ...methods,
      filterTableData,
      ...toRefs(staticData)
    }
}


})



</script>

<style scoped>
.demo-pagination-block + .demo-pagination-block {
margin-top: 10px;
}
.demo-pagination-block .demonstration {
margin-bottom: 16px;
}
</style>
<style scoped>
.app_content{
  
  margin-top: 30px;
  margin-left: 10px;
}
.mb8{
  margin-bottom: 10px;
}
</style>